package com.demo.accessibilitykeeper;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

/**
 * 应用隐藏工具类
 * 提供多种隐藏应用图标的方法
 */
public class AppHider {
    
    private static final String TAG = "AppHider";
    
    private Context context;
    private PackageManager packageManager;
    
    public AppHider(Context context) {
        this.context = context;
        this.packageManager = context.getPackageManager();
    }
    
    /**
     * 方案1: PackageManager隐藏 (Android 10+)
     * 通过禁用组件来隐藏应用图标
     */
    public void hideAppIcon() {
        try {
            Log.d(TAG, "🔒 HIDING_APP_ICON - Using PackageManager method");
            
            String packageName = context.getPackageName();
            Log.d(TAG, "📦 PACKAGE_NAME - " + packageName);
            
            // 获取所有启动器组件
            List<ComponentName> launcherComponents = getAllLauncherComponents();
            Log.d(TAG, "🔍 FOUND_COMPONENTS_COUNT - " + launcherComponents.size());
            
            if (launcherComponents.isEmpty()) {
                Log.w(TAG, "⚠️ NO_LAUNCHER_COMPONENTS_FOUND - Trying alternative method");
                // 如果没找到组件，尝试直接禁用主Activity
                hideMainActivityDirectly();
                return;
            }
            
            // 禁用所有启动器组件
            for (ComponentName component : launcherComponents) {
                int currentState = packageManager.getComponentEnabledSetting(component);
                Log.d(TAG, "🔍 COMPONENT_STATE - " + component.getClassName() + " = " + getStateString(currentState));
                
                if (currentState != PackageManager.COMPONENT_ENABLED_STATE_DISABLED) {
                    packageManager.setComponentEnabledSetting(
                        component,
                        PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                        PackageManager.DONT_KILL_APP
                    );
                    Log.d(TAG, "✅ COMPONENT_DISABLED - " + component.getClassName());
                } else {
                    Log.d(TAG, "ℹ️ COMPONENT_ALREADY_DISABLED - " + component.getClassName());
                }
            }
            
            // 强制刷新桌面
            forceRefreshLauncher();
            
            Log.i(TAG, "🎯 APP_ICON_HIDDEN - All launcher components disabled");
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_HIDING_APP_ICON", e);
        }
    }
    
    /**
     * 直接隐藏主Activity（备用方法）
     */
    private void hideMainActivityDirectly() {
        try {
            String packageName = context.getPackageName();
            ComponentName mainActivity = new ComponentName(packageName, MainActivity.class.getName());
            
            int currentState = packageManager.getComponentEnabledSetting(mainActivity);
            Log.d(TAG, "🔍 MAIN_ACTIVITY_STATE - " + getStateString(currentState));
            
            if (currentState != PackageManager.COMPONENT_ENABLED_STATE_DISABLED) {
                packageManager.setComponentEnabledSetting(
                    mainActivity,
                    PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                    PackageManager.DONT_KILL_APP
                );
                Log.d(TAG, "✅ MAIN_ACTIVITY_DISABLED - " + mainActivity.getClassName());
            }
            
            // 强制刷新桌面
            forceRefreshLauncher();
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_HIDING_MAIN_ACTIVITY_DIRECTLY", e);
        }
    }
    
    /**
     * 获取组件状态字符串
     */
    private String getStateString(int state) {
        switch (state) {
            case PackageManager.COMPONENT_ENABLED_STATE_DEFAULT:
                return "DEFAULT";
            case PackageManager.COMPONENT_ENABLED_STATE_ENABLED:
                return "ENABLED";
            case PackageManager.COMPONENT_ENABLED_STATE_DISABLED:
                return "DISABLED";
            case PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER:
                return "DISABLED_USER";
            case PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED:
                return "DISABLED_UNTIL_USED";
            default:
                return "UNKNOWN(" + state + ")";
        }
    }
    
    /**
     * 方案2: 动态组件别名 (Android 11+)
     * 通过动态启用/禁用不同的别名来隐藏图标
     */
    public void setupDynamicAlias() {
        try {
            Log.d(TAG, "🔄 SETTING_UP_DYNAMIC_ALIAS - Using dynamic alias method");
            
            String packageName = context.getPackageName();
            
            // 预定义的别名列表
            String[] aliases = {
                packageName + ".BlueAlias",
                packageName + ".TransparentAlias",
                packageName + ".HiddenAlias"
            };
            
            // 禁用所有别名
            for (String alias : aliases) {
                ComponentName aliasComponent = new ComponentName(packageName, alias);
                if (packageManager.getComponentEnabledSetting(aliasComponent) != PackageManager.COMPONENT_ENABLED_STATE_DISABLED) {
                    packageManager.setComponentEnabledSetting(
                        aliasComponent,
                        PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                        PackageManager.DONT_KILL_APP
                    );
                    Log.d(TAG, "✅ ALIAS_DISABLED - " + alias);
                }
            }
            
            // 禁用主Activity的启动器
            ComponentName mainActivity = new ComponentName(packageName, MainActivity.class.getName());
            if (packageManager.getComponentEnabledSetting(mainActivity) != PackageManager.COMPONENT_ENABLED_STATE_DISABLED) {
                packageManager.setComponentEnabledSetting(
                    mainActivity,
                    PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                    PackageManager.DONT_KILL_APP
                );
                Log.d(TAG, "✅ MAIN_ACTIVITY_DISABLED");
            }
            
            // 刷新桌面
            refreshLauncher();
            
            Log.i(TAG, "🎯 DYNAMIC_ALIAS_SETUP - All aliases disabled");
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_SETTING_UP_DYNAMIC_ALIAS", e);
        }
    }
    
    /**
     * 方案3: 完全隐藏 (隐藏所有启动器入口)
     */
    public void hideAllLauncherEntries() {
        try {
            Log.d(TAG, "🚫 HIDING_ALL_LAUNCHER_ENTRIES - Complete hiding method");
            
            String packageName = context.getPackageName();
            
            // 获取所有启动器组件
            List<ComponentName> launcherComponents = getAllLauncherComponents();
            
            // 禁用所有启动器组件
            for (ComponentName component : launcherComponents) {
                packageManager.setComponentEnabledSetting(
                    component,
                    PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                    PackageManager.DONT_KILL_APP
                );
                Log.d(TAG, "✅ LAUNCHER_COMPONENT_DISABLED - " + component.getClassName());
            }
            
            // 移除所有快捷方式
            removeAllShortcuts();
            
            // 刷新桌面
            refreshLauncher();
            
            Log.i(TAG, "🎯 ALL_LAUNCHER_ENTRIES_HIDDEN - Complete hiding successful");
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_HIDING_ALL_LAUNCHER_ENTRIES", e);
        }
    }
    
    /**
     * 恢复应用图标显示
     */
    public void showAppIcon() {
        try {
            Log.d(TAG, "👁️ SHOWING_APP_ICON - Restoring app icon");
            
            String packageName = context.getPackageName();
            
            // 启用主Activity
            ComponentName mainActivity = new ComponentName(packageName, MainActivity.class.getName());
            packageManager.setComponentEnabledSetting(
                mainActivity,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP
            );
            
            // 禁用其他别名
            String[] aliases = {
                packageName + ".BlueAlias",
                packageName + ".TransparentAlias",
                packageName + ".HiddenAlias"
            };
            
            for (String alias : aliases) {
                ComponentName aliasComponent = new ComponentName(packageName, alias);
                packageManager.setComponentEnabledSetting(
                    aliasComponent,
                    PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                    PackageManager.DONT_KILL_APP
                );
            }
            
            // 刷新桌面
            refreshLauncher();
            
            Log.i(TAG, "🎯 APP_ICON_SHOWN - Main activity enabled");
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_SHOWING_APP_ICON", e);
        }
    }
    
    /**
     * 切换到透明图标
     */
    public void switchToTransparentIcon() {
        try {
            Log.d(TAG, "👻 SWITCHING_TO_TRANSPARENT_ICON");
            
            String packageName = context.getPackageName();
            
            // 禁用主Activity
            ComponentName mainActivity = new ComponentName(packageName, MainActivity.class.getName());
            packageManager.setComponentEnabledSetting(
                mainActivity,
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP
            );
            
            // 启用透明别名
            ComponentName transparentAlias = new ComponentName(packageName, packageName + ".TransparentAlias");
            packageManager.setComponentEnabledSetting(
                transparentAlias,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP
            );
            
            // 禁用其他别名
            String[] otherAliases = {
                packageName + ".BlueAlias",
                packageName + ".HiddenAlias"
            };
            
            for (String alias : otherAliases) {
                ComponentName aliasComponent = new ComponentName(packageName, alias);
                packageManager.setComponentEnabledSetting(
                    aliasComponent,
                    PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                    PackageManager.DONT_KILL_APP
                );
            }
            
            // 刷新桌面
            refreshLauncher();
            
            Log.i(TAG, "🎯 TRANSPARENT_ICON_ACTIVATED");
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_SWITCHING_TO_TRANSPARENT_ICON", e);
        }
    }
    
    /**
     * 获取所有启动器组件
     */
    private List<ComponentName> getAllLauncherComponents() {
        List<ComponentName> components = new ArrayList<>();
        String packageName = context.getPackageName();
        
        try {
            Log.d(TAG, "🔍 SEARCHING_LAUNCHER_COMPONENTS - Package: " + packageName);
            
            // 查询所有启动器Activity
            Intent launcherQuery = new Intent(Intent.ACTION_MAIN);
            launcherQuery.addCategory(Intent.CATEGORY_LAUNCHER);
            List<ResolveInfo> resolveInfos = packageManager.queryIntentActivities(launcherQuery, 0);
            
            Log.d(TAG, "🔍 TOTAL_RESOLVE_INFOS - " + (resolveInfos != null ? resolveInfos.size() : 0));
            
            if (resolveInfos != null) {
                for (ResolveInfo info : resolveInfos) {
                    if (info.activityInfo != null) {
                        Log.d(TAG, "🔍 CHECKING_COMPONENT - " + info.activityInfo.packageName + "/" + info.activityInfo.name);
                        
                        if (packageName.equals(info.activityInfo.packageName)) {
                            ComponentName component = new ComponentName(
                                info.activityInfo.packageName,
                                info.activityInfo.name
                            );
                            components.add(component);
                            Log.d(TAG, "✅ FOUND_LAUNCHER_COMPONENT - " + info.activityInfo.name);
                        }
                    }
                }
            }
            
            // 如果没找到任何组件，尝试手动添加主Activity
            if (components.isEmpty()) {
                Log.w(TAG, "⚠️ NO_COMPONENTS_FOUND - Adding MainActivity manually");
                ComponentName mainActivity = new ComponentName(packageName, MainActivity.class.getName());
                components.add(mainActivity);
                Log.d(TAG, "✅ ADDED_MAIN_ACTIVITY_MANUALLY - " + MainActivity.class.getName());
            }
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_GETTING_LAUNCHER_COMPONENTS", e);
        }
        
        Log.d(TAG, "🔍 FINAL_COMPONENTS_COUNT - " + components.size());
        return components;
    }
    
    /**
     * 移除所有快捷方式
     */
    private void removeAllShortcuts() {
        try {
            // Android 7.1+ 动态快捷方式
            if (Build.VERSION.SDK_INT >= 25) {
                android.content.pm.ShortcutManager sm = (android.content.pm.ShortcutManager) 
                    context.getSystemService(Context.SHORTCUT_SERVICE);
                if (sm != null) {
                    List<android.content.pm.ShortcutInfo> pinned = sm.getPinnedShortcuts();
                    List<String> ids = new ArrayList<>();
                    if (pinned != null) {
                        for (android.content.pm.ShortcutInfo s : pinned) {
                            ids.add(s.getId());
                        }
                    }
                    if (!ids.isEmpty()) {
                        sm.disableShortcuts(ids);
                    }
                    sm.removeAllDynamicShortcuts();
                    Log.d(TAG, "✅ DYNAMIC_SHORTCUTS_REMOVED");
                }
            }
            
            // 旧版快捷方式
            Intent uninstall = new Intent("com.android.launcher.action.UNINSTALL_SHORTCUT");
            uninstall.putExtra(Intent.EXTRA_SHORTCUT_NAME, context.getString(context.getApplicationInfo().labelRes));
            Intent launchIntent = new Intent(Intent.ACTION_MAIN);
            launchIntent.addCategory(Intent.CATEGORY_LAUNCHER);
            launchIntent.setClassName(context.getPackageName(), MainActivity.class.getName());
            uninstall.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launchIntent);
            context.sendBroadcast(uninstall);
            Log.d(TAG, "✅ LEGACY_SHORTCUTS_REMOVED");
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_REMOVING_SHORTCUTS", e);
        }
    }
    
    /**
     * 刷新桌面
     */
    private void refreshLauncher() {
        try {
            // 回到桌面
            Intent home = new Intent(Intent.ACTION_MAIN);
            home.addCategory(Intent.CATEGORY_HOME);
            home.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(home);
            
            // 通知桌面刷新
            notifyLaunchersToRefresh();
            
            Log.d(TAG, "🔄 LAUNCHER_REFRESHED");
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_REFRESHING_LAUNCHER", e);
        }
    }
    
    /**
     * 强制刷新桌面（更强的方法）
     */
    private void forceRefreshLauncher() {
        try {
            Log.d(TAG, "🔄 FORCE_REFRESHING_LAUNCHER - Using enhanced refresh method");
            
            // 方法1: 回到桌面
            Intent home = new Intent(Intent.ACTION_MAIN);
            home.addCategory(Intent.CATEGORY_HOME);
            home.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            context.startActivity(home);
            
            // 方法2: 通知桌面刷新
            notifyLaunchersToRefresh();
            
            // 方法3: 延迟刷新（给桌面时间处理）
            new android.os.Handler(android.os.Looper.getMainLooper()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    try {
                        // 再次通知刷新
                        notifyLaunchersToRefresh();
                        Log.d(TAG, "🔄 DELAYED_LAUNCHER_REFRESH - Completed");
                    } catch (Exception e) {
                        Log.e(TAG, "❌ ERROR_DELAYED_REFRESH", e);
                    }
                }
            }, 1000);
            
            Log.d(TAG, "🔄 FORCE_LAUNCHER_REFRESHED - Enhanced refresh completed");
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_FORCE_REFRESHING_LAUNCHER", e);
        }
    }
    
    /**
     * 通知常见桌面刷新
     */
    private void notifyLaunchersToRefresh() {
        try {
            // 通用刷新广播
            context.sendBroadcast(new Intent("com.android.launcher.action.ACTION_UPDATE_ICON")
                .putExtra("package_name", context.getPackageName()));
            context.sendBroadcast(new Intent("com.android.launcher.action.REFRESH_LAUNCHER"));
            
            // MIUI
            context.sendBroadcast(new Intent("miui.launcher.ACTION_INSTALL_SHORTCUT").setPackage("com.miui.home"));
            context.sendBroadcast(new Intent("miui.launcher.ACTION_UNINSTALL_SHORTCUT").setPackage("com.miui.home"));
            
            // 华为 EMUI、荣耀 MagicUI
            context.sendBroadcast(new Intent("com.huawei.android.launcher.action.CHANGE_SHORTCUT").setPackage("com.huawei.android.launcher"));
            
            Log.d(TAG, "📡 LAUNCHER_REFRESH_NOTIFICATIONS_SENT");
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_NOTIFYING_LAUNCHERS", e);
        }
    }
    
    /**
     * 检查应用图标是否隐藏
     */
    public boolean isAppIconHidden() {
        try {
            String packageName = context.getPackageName();
            ComponentName mainActivity = new ComponentName(packageName, MainActivity.class.getName());
            
            int state = packageManager.getComponentEnabledSetting(mainActivity);
            boolean isHidden = (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED);
            
            Log.d(TAG, "🔍 APP_ICON_STATUS - Hidden: " + isHidden + ", State: " + state);
            return isHidden;
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_CHECKING_APP_ICON_STATUS", e);
            return false;
        }
    }
    
    /**
     * 获取当前图标状态
     */
    public String getCurrentIconStatus() {
        try {
            String packageName = context.getPackageName();
            
            // 检查主Activity
            ComponentName mainActivity = new ComponentName(packageName, MainActivity.class.getName());
            if (packageManager.getComponentEnabledSetting(mainActivity) == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
                return "MAIN_ACTIVITY";
            }
            
            // 检查别名
            String[] aliases = {
                packageName + ".BlueAlias",
                packageName + ".TransparentAlias",
                packageName + ".HiddenAlias"
            };
            
            for (String alias : aliases) {
                ComponentName aliasComponent = new ComponentName(packageName, alias);
                if (packageManager.getComponentEnabledSetting(aliasComponent) == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
                    return alias.substring(alias.lastIndexOf('.') + 1);
                }
            }
            
            return "HIDDEN";
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_GETTING_ICON_STATUS", e);
            return "UNKNOWN";
        }
    }
}
